﻿using System;
using System.Web.UI;

namespace NazTek.Extension.Clr4
{
    /// <summary>
    /// StateBag extension methods
    /// </summary>
    public static class StateBagExtension
    {
        /// <summary>
        /// Gets enum value from state bag
        /// </summary>
        /// <typeparam name="T">Type of enum value</typeparam>
        /// <param name="bag">Enum value store instance</param>
        /// <param name="keyPostfix">Enum value identifier postfix</param>
        /// <returns>Specificcally typed enum value for the specified key</returns>
        public static T GetEnumValue<T>(this StateBag bag, string keyPostfix = "")
        {
            Parameter.ValidateEnum<T>();
            return (T)bag[BuildKey(typeof(T), keyPostfix)];
        }
        /// <summary>
        /// Stores enum value in state bag
        /// </summary>
        /// <typeparam name="T">Type of enum value to store</typeparam>
        /// <param name="bag">Enum value store instance</param>
        /// <param name="value">The enum value to store</param>
        /// <param name="keyPostfix">Enum value identifier postfix</param>
        public static void SetEnumValue<T>(this StateBag bag, T value, string keyPostfix = "")
        {
            Parameter.ValidateEnum<T>();
            bag[BuildKey(typeof(T), keyPostfix)] = value;
        }
        /// <summary>
        /// Builds stored value identifying key by concatenating type and postfix
        /// </summary>
        private static Func<Type, string, string> BuildKey
            = (enumType, keyPostfix) => string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}{1}", enumType, keyPostfix);
    }
}